package cn.zhm;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *     Tomcat老版本IO网络编程
 * </p>
 * @Author: ZhongHaoMing
 * @emali: zhonghaoming@bosssoft.com
 * @since: 1.8
 * @Date: 2021/10/26 - 17:28
 */
public class IoMain {
    public static long num = 0L;

    public static void main(String[] args) throws Exception{
        ExecutorService executorService =  new ThreadPoolExecutor(0, 20,
                60L, TimeUnit.SECONDS,new SynchronousQueue());
        ServerSocket socket = new ServerSocket(8080);
        System.out.println("服务器启动");
        while (true){
            Socket accept = socket.accept();
            num++;
            executorService.execute(()->{
                message(accept);
            });
            if(accept.isClosed()){
                break;
            }
        }
        System.out.println("一共"+num+"个用户");
    }
    private static void message(Socket accept){
        try {
            InputStream inputStream = accept.getInputStream();
            OutputStream outputStream = accept.getOutputStream();
            byte[] bytes = new byte[1024];

            while (inputStream.read(bytes)!=-1){
                outputStream.write(ReturnHtml.ret("index.html").getBytes(StandardCharsets.UTF_8));
                String s = new String(bytes);
                System.out.println(s);
                System.out.println("\n\n\n--------------------------\n\n\n");
                accept.close();
                return;
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
